<?php

/**
 * 
 */

class NfileApi extends ApiBase{


	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
	}

	public function get($id){
		$id = intval($id);
		$mysql = n_api("mysql")->cname('weixin');
		
		$finfo = $mysql->get("nfile_main",$id);
		if(empty($finfo)){
			return n_state(FALSE, "找不到文件");
		}
		
		$rs = n_state(TRUE, "获取成功");
		$rs['path'] = $this->getFiledir($id).$id;
		$rs['url'] = $this->getUrl($id).$id;
		$rs['showurl'] = n_url("nfile",'show',array('id'=>$id));
		$rs['downloadurl'] = n_url("nfile",'download',array('id'=>$id));
		$rs['finfo'] = $finfo;
		return $rs;
	}



	public function getMime($id){
		return n_api("mysql")->cname('weixin')->get("nfile_mime",$id);
	}
	public function getFileMime($filename){
		if(!file_exists($filename)){
			throw new PException("找不到文件");
		}
		$mime = addslashes(mime_content_type($filename));
		$type = explode("/", $mime);
		$mysql = n_api("mysql")->cname('weixin');
		$mime = $mysql->fetchFirst("select * from nfile_mime where type='{$type[0]}' and subtype='{$type[1]}'");
		if(empty($mime)){
			$id = $mysql->insert("nfile_mime",array('type'=>$type[0],'subtype'=>$type[1]));
			$rs = array('id'=>$id,'type'=>$type[0],"subtype"=>$typ[1]);
		}else{
			$rs = $mime;
		}
		$rs['mime'] = $rs['type'].'/'.$rs['subtype'];
		return $rs;
	}
	public function getName($filename){
		$name = explode('.', $filename);
		array_pop($name);
		return 0==count($name)?$filename:implode('.',$name);
		
	}
	public function getExt($filename){
		$ext = explode('.', $filename);
		return 2<count($ext)?'':strtolower(array_pop($ext));
		
	}
	
	public function getByMd5($filename){
		if(!file_exists($filename)){
			throw new PException("找不到文件1".$filename);
		}
		$md5 = md5_file($filename);
		$mysql = n_api("mysql")->cname('weixin');
		return $mysql->fetchFirst("select * from nfile_main where md5='{$md5}'");
	}

	public function getFiledir($id){
		$pernum = 128;
		$rs = '';
		$arr = str_split($id,2);
		//sort($arr);
		$rs .= '/'.implode('/',$arr).'/';
		return $rs;
	}
	public function getUrl($id){
		return n_url('nfile','get',array('id'=>$id));
		
	}

	/**
	 * 获取虚拟目录
	 */
	public function getVdir($id){
		return n_api("mysql")->cname('weixin')->get("nfile_dir",$id);
	}

	/**
	 * 这个函数非常纯粹的只是保存文件。
	 * 硬盘保存，数据库保存
	 */
	public function save($src,$name='',$ext='',$descript='',$type='RENAME'){
		$rs = $this->getByMd5($src);	
		$mysql = n_api("mysql")->cname('weixin');
		
		$mulist = $this->getMu();

		if(empty($rs)){
			$mime = $this->getFileMime($src);
			$data['md5'] = md5_file($src);
			$data['name'] = $name;
			$data['ext'] = $ext;
			$data['descript'] = $descript;
			$data['size'] = filesize($src);
			$data['mime_id'] = $mime['id'];
			$data['ctime'] = time();
			$data['icon_id'] = 0;
			$data['id'] = $mysql->insert("nfile_main",$data);
			$mu = $mulist[array_rand($mulist)];
			$dir = $mu['dir'].$this->getFiledir($data['id']);
			if(!is_dir($dir)){
				n_api("common")->mkdir($dir);
			}
			//提供复制+转移的操作
			if('copy'==strtolower($type)){
				if(!copy($src, $dir.'/'.$data['id'])){
					throw new PException("文件复制失败".$dir);
				}				
			}else{
				if(!rename($src, $dir.'/'.$data['id'])){
					throw new PException("文件创建失败".$dir);
				}
			}
			$mysql->insert("nfile_copy",array('mu_id'=>$mu['id'],'main_id'=>$data['id'],'ctime'=>N_NOW));
			$rs = $data;
		}
		return $rs;
	}


	/**
	 * 对上传的文件进行保存，这里不涉及到用户的信息关联
	 */
	public function uploadSave(){

		$mysql = n_api("mysql")->cname('weixin');

		if(!isset($_FILES['file'])){
			throw new PException("请指定上传变量为file");
		}
		if(0!=$_FILES['file']['error']){
			throw new PException("文件未正确上传");
		}
		$file = $_FILES['file'];

		//获取附加的内容
		$ext = $this->getExt($file['name']);
		$name = $this->getName($file['name']);
		$saveRs = $this->save($file['tmp_name'],$name,$ext);
		return $saveRs;		
	}
	
	public function ppLink($fid='',$scode=''){

		$mysql = n_api("mysql")->cname('weixin');
		$ppid = $_SESSION['ppid'];

		if(!empty($fid)){
			$dirid = $fid;
			$dinfo = $mysql->get("nfile_dir",$fid);
			if(empty($dinfo)){
				throw new PException("找不到目录");
			}
			$scode = $dinfo['scode'];
			
		}elseif(!empty($scode)){
			$scode = $scode;
			$dirid = 0;
		}else{
			throw new PException("请求错误");
		}

		$saveRs = $this->uploadSave();
		n_api("mysql")->cname('weixin')->insert("nfile_link",array("scode"=>$scode,"dir_id"=>$dirid,"ppid"=>$ppid,"main_id"=>$saveRs['id'],"name"=>$name,"ctime"=>time()));
		return n_state(true, "上传成功");
		
	}
	
	public function download($id){
		$mysql = n_api("mysql")->cname('weixin');
		
		$finfo = $this->get($id);

		if(!$finfo['state']){
			header("HTTP/1.0 404 Not Found");
			exit;
		}
		if(empty($finfo['finfo']['name'])){
			$finfo['finfo']['name'] = $finfo['finfo']['md5']; 
		}
		header("Content-type: application/octet-stream;charset=utf8");
		header("Accept-Ranges: bytes");
		header("Accept-Length: {$finfo['finfo']['size']}");
		header("Content-Disposition: attachment; filename={$finfo['finfo']['name']}.{$finfo['finfo']['ext']}");
		echo file_get_contents($finfo['url']);
		exit;
		
	}

	public function show($id){
		
		$finfo = $this->get($id);

		if(!$finfo['state']){
			header("HTTP/1.0 404 Not Found");
			exit;
		}
		if(empty($finfo['finfo']['name'])){
			$finfo['finfo']['name'] = $finfo['finfo']['md5']; 
		}
		
		$mime = $this->getMime($finfo['finfo']['mime_id']);
		header("Content-Type: ".$mime['type'].'/'.$mime['subtype']);
		echo file_get_contents($finfo['url']);
		exit;
		
	}

	
	public function getMu(){
		return n_api("mysql")->cname('weixin')->selectIndex("select id,ip,dir,size,usize,state from nfile_mu where isdel='N'");
	}
	
	
	public function copy($mainId,$ip,$sfile,$dfile){

		$ddir = dirname($dfile);
		if('localhost'==$ip || '127.0.0.1'==$ip){
			//system("su lnmp;");
			system("mkdir -p {$ddir};");
			system("cp -Rp {$sfile} {$dfile};");
			system("chown lnmp {$dfile};");
			system("chgrp lnmp {$dfile};");
			//system("exit;");
		}else{
			system("ssh root@{$ip} mkdir -p {$ddir}; exit;");
			system("scp {$sfile} root@{$ip}:{$dfile}");
			//system("rm -f {$tmpPath}");
		}

	}

	public function getCopyList($id){
		return n_api("mysql")->cname('weixin')->select("select * from nfile_copy where main_id={$id}");
	}	
}